﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Employees_ContractList : System.Web.UI.Page
{
    private Srvtools.WebDataSet WMaster;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();




            MasterPage_MasterPage master = (MasterPage_MasterPage)this.Page.Master;
            master.HelpHref = "";
            master.PageName = "人事合同列表";
            master.PicUrl = "~/image/PageIcon/hetong.jpg";
            master.IntiBar();
        }
    }

    private void InitializeComponent(bool action)
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Employees_ContractList));
        this.WMaster = new Srvtools.WebDataSet();
        ((System.ComponentModel.ISupportInitialize)(this.WMaster)).BeginInit();
        // 
        // WMaster
        // 
        this.WMaster.Active = action;
        this.WMaster.AlwaysClose = false;
        this.WMaster.PacketRecords = -1;
        this.WMaster.Position = -1;
        this.WMaster.RemoteName = "SEmployees.ViewContract";
        this.WMaster.ServerModify = false;
        ((System.ComponentModel.ISupportInitialize)(this.WMaster)).EndInit();

    }

    private void Bind()
    {
        FullYear.Style.Add("display", "none");
        Nor.Style.Add("display", "block");

        if (Request["IsSearch"] != null)
        {
            if (Request["IsSearch"].ToString() == "1")
            {
                SBind();
            }
        }
        else
        {
            ddlStatus.SelectedValue = "0";
            InitializeComponent(false);
            Master.DataSource = WMaster;
            wgvMaster.Visible = false;
        }
    }

    protected void Search_Click(object sender, EventArgs e)
    {
        Search.CssClass = "OnHover";

        //InitializeComponent(true);

        //Search.CssClass = "OnHover";
        string url = "IsSearch=1";
        switch (ddlStatus.SelectedValue)
        {

            case "0":
                url += "&ddl=0";

                string strDep = Depart.SelectDepmanetId;

                if (strDep != "0" && strDep != "")
                {
                    url += "&dep=" + strDep;
                }
                else
                {
                    url += "&dep=";

                }


                string sname = SelUser.EmpName;
                if (sname != "")
                {
                    url += "&name=" + Server.UrlEncode(sname);

                }
                else
                {
                    url += "&name=";

                }

                url += "&so=" + ddlTimeOption.SelectedValue;

                if (Accession.Text != "")
                {
                    url += "&bt=" + Server.UrlEncode(Accession.Text);
                }
                else
                {
                    url += "&bt=";
                }

                if (Dimission.Text != "")
                {
                    url += "&et=" + Server.UrlEncode(Dimission.Text);
                }
                else
                {
                    url += "&et=";
                }

                break;
            case "1":
                url += "&ddl=1";


                break;
            case "2":
                url += "&ddl=2";


                break;
            case "3":
                url += "&ddl=3";


                break;
            case "4":
                url += "&ddl=4";
                break;
            case "5":
                url += "&ddl=5&y=" + FYmonth.SelectedValue;
                break;

        }

        Response.Redirect("ContractList.aspx?" + url);


    }

    private void SBind()
    {
        Search.CssClass = "OnHover";

        InitializeComponent(true);

        switch (Request["ddl"].ToString())
        {
            case "0":
                ddlStatus.SelectedValue = "0";
                string strDep = Request["dep"].ToString();
                string sname = Server.UrlDecode(Request["name"]);
                string bt = Server.UrlDecode(Request["bt"]);
                string et = Server.UrlDecode(Request["et"]);
                string so = Request["so"].ToString();


                if (strDep != "0" && strDep != "")
                {
                    Depart.IsAfterBind = strDep;
                    strDep = " Employees.DepartmentId like ('" + strDep + "%')";
                }
                else
                {
                    strDep = " Employees.DepartmentId <> -1";
                }



                if (sname != "")
                {
                    SelUser.EmpName = sname;
                    sname = " And EmpName like ('%" + sname + "%')";
                }
                else
                {

                    sname = "";
                }

                ddlTimeOption.SelectedValue = so;
                if (so == "0")
                {
                    if (bt != "")
                    {
                        Accession.Text = bt;
                        bt = " And Contractbegin > '" + bt + " 00:00:00'";
                    }
                    else
                    {
                        bt = "";
                    }

                    if (et != "")
                    {
                        Dimission.Text = et;
                        et = " And Contractbegin < '" + et + " 23:59:59'";
                    }
                    else
                    {
                        et = "";
                    }
                }
                else
                {
                    if (bt != "")
                    {
                        Accession.Text = bt;
                        bt = " And Contractend > '" + bt + " 00:00:00'";
                    }
                    else
                    {
                        bt = "";
                    }

                    if (et != "")
                    {
                        Dimission.Text = et;
                        et = " And Contractend < '" + et + " 23:59:59'";
                    }
                    else
                    {
                        et = "";
                    }
                }


                WMaster.SetWhere(strDep + sname + bt + et);
                break;
            case "1":
                ddlStatus.SelectedValue = "1";
                WMaster.SetWhere("datediff(month,getdate(),Contractend) < 1 and Contract.overdue=0");
                break;
            case "2":
                ddlStatus.SelectedValue = "2";
                WMaster.SetWhere("(Contractbegin is null or Contractbegin is null)");
                break;
            case "3":
                ddlStatus.SelectedValue = "3";
                WMaster.SetWhere("datediff(month,getdate(),Contractend) = 0");
                break;
            case "4":
                ddlStatus.SelectedValue = "4";
                WMaster.SetWhere("datediff(month,getdate(),Contractend) = 1");
                break;
            case "5":
                ddlStatus.SelectedValue = "5";
                FYmonth.SelectedValue = Request["y"].ToString();

                WMaster.SetWhere("CONVERT(varchar(12) , Contractend, 112) like '____" + Request["y"].ToString() + "__'");
                FullYear.Style.Add("display", "block");
                Nor.Style.Add("display", "none");
                break;
        }

        Master.DataSource = WMaster;

        wgvMaster.Visible = true;
    }

    protected void wgvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;
            if (drv["Contractend"].ToString() != "")
                ((Label)e.Row.FindControl("Day")).Text = toResult(Convert.ToDateTime(drv["Contractend"]), DateTime.Now, "d")[0].ToString();

            ImageButton imb = (ImageButton)e.Row.FindControl("imb");

            //if (drv["ContractId"].ToString() == "")
            //{
            imb.Attributes.Add("onclick", "location.href='ContractDetail.aspx?eid=" + drv["EmployeeID"].ToString() + "&ename=" + Server.UrlEncode(drv["EmpName"].ToString()) +
                "&action=edit&redurl=" + Server.UrlEncode(Request.Url.ToString()) + "';return false;");

            //}
            //else
            //{
            //imb.Attributes.Add("onclick", "location.href='ContractDetail.aspx?cid=" + drv["ContractId"].ToString() +
            //    "&eid=" + drv["EmployeeID"].ToString() + "&ename=" + Server.UrlEncode(drv["EmpName"].ToString()) + "&redurl=" + Server.UrlEncode(Request.Url.ToString()) + "';return false;");
            //}
        }
    }


    public int[] toResult(DateTime d1, DateTime d2, string type)
    {
        #region 数据初始化
        DateTime max;
        DateTime min;
        int year;
        int month;
        int tempYear, tempMonth;

        max = d1;
        min = d2;

        tempYear = max.Year;
        tempMonth = max.Month;
        if (max.Month < min.Month)
        {
            tempYear--;
            tempMonth = tempMonth + 12;
        }
        year = tempYear - min.Year;
        month = tempMonth - min.Month;
        #endregion
        #region 按条件计算
        if (type == "d")
        {
            TimeSpan ts = max - min;

            return new int[] { ts.Days };
        }
        if (type == "m")
        {
            return new int[] { month + year * 12 };
        }
        if (type == "y")
        {
            return new int[] { year };
        }
        return new int[] { year, month };
        #endregion
    }

    protected void DownLoad_Click(object sender, EventArgs e)
    {
        try
        {
            object obj = Master.InnerDataSet;

            string path = MapPath("~/UploadFile/Template/");

            DataTable dt = ((DataSet)obj).Tables[0];


            if (dt.Rows.Count <= 0)
            {
                ClientScript.RegisterStartupScript(GetType(), "Msg", "alert('没有记录')", true);
                return;
            }
            DataTable dts = GetDataTable();

            foreach (DataRow dr in dt.Rows)
            {
                DataRow SR = dts.NewRow();
                SR["合同编号"] = dr["ContractId"];
                SR["员工编号"] = dr["EmployeeID"];
                SR["员工姓名"] = dr["EmpName"];
                SR["部门"] = dr["DepartmentName"];
                SR["职位"] = dr["JobName"];
                SR["入职日期"] = dr["Accession"];
                SR["合同开始"] = dr["Contractbegin"];
                SR["合同结束"] = dr["ContractEnd"];
                SR["到期天数"] = dr["Contractend"].ToString() != "" ? toResult(Convert.ToDateTime(dr["Contractend"]), DateTime.Now, "d")[0].ToString() : "";

                dts.Rows.Add(SR);
            }

            DataTable dtt = dts.Clone();
            dtt.Merge(dts);
            Srvtools.InfoDataSet ids = new Srvtools.InfoDataSet();
            ids.RemoteName = "GLModule.cmdColDEF";
            ids.RealDataSet.Tables.Add(dtt);

            ids.ToExcel(0, path + "empcontract.xls");


            System.IO.FileInfo fn = new System.IO.FileInfo(path + "empcontract.xls");

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fn.Name);
            HttpContext.Current.Response.WriteFile(fn.FullName);
            HttpContext.Current.Response.End();
        }
        catch
        {

        }
    }

    private DataTable GetDataTable()
    {
        DataTable WTable = new DataTable("DownLoadDT");
        {
            WTable.Columns.Add(new DataColumn("合同编号", typeof(Int32)));
            WTable.Columns.Add(new DataColumn("员工编号", typeof(Int32)));
            WTable.Columns.Add(new DataColumn("员工姓名", typeof(string)));
            WTable.Columns.Add(new DataColumn("部门", typeof(string)));
            WTable.Columns.Add(new DataColumn("职位", typeof(string)));
            WTable.Columns.Add(new DataColumn("入职日期", typeof(string)));
            WTable.Columns.Add(new DataColumn("合同开始", typeof(string)));
            WTable.Columns.Add(new DataColumn("合同结束", typeof(string)));
            WTable.Columns.Add(new DataColumn("到期天数", typeof(string)));
        }
        return WTable;
    }
}
